package com.cn.appcore.base

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.view.MenuItem
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.cn.appcore.config.AppConfig
import com.cn.appcore.ext.showToast
import com.cn.appcore.http.error.ResponseThrowable
import com.cn.appcore.utils.KeyBoardUtil
import com.cn.appcore.utils.loader.LatteLoader
import com.gyf.barlibrary.ImmersionBar
import rx.Subscription

/**
 * 项目：ForeignExchange
 * 包名：com.cn.appcore.base
 * 类名：BaseVMActivity2
 * 创建时间：2022/10/3 14:21
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
abstract class BaseVMActivity <VM : BaseViewModel,T: ViewDataBinding> : AppCompatActivity() {

    protected var pageNo=1
    protected var pageSize=15
    lateinit var mViewModel: VM
    lateinit var binding:T

    //RxBus
    protected var rxBusSubscription: Subscription? = null
    //状态栏
    protected var mImmersionBar: ImmersionBar? = null

    private val loadingDialog by lazy { LatteLoader.getLoading(this) }
    protected open var showLoadingDialog: Boolean = true


    override fun onCreate(savedInstanceState: Bundle?) {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        super.onCreate(savedInstanceState)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT // 强制竖屏
        AppConfig.getActivityManager()?.pushActivity(this)
        binding = DataBindingUtil.setContentView(this,attachLayoutRes())
        initVM()
        //初始化沉浸式
        if (isImmersionBarEnabled()) {
            initImmersionBar()
        }
        initBar()
//        //注册 UI事件
//        registerUIChange()
        initView()
        initData()
        initClickListener()
        initRequestObserver()
        initResultLauncher()
    }
    @Suppress("DEPRECATION")
    private fun initVM() {
        if (attachVMClass() == null) {
            throw RuntimeException("ViewModel must not be null.")
        }
        attachVMClass()?.let {
            mViewModel = ViewModelProviders.of(this).get(it)
            lifecycle.addObserver(mViewModel)
        }
    }
    protected open fun showLoading() {
        if (showLoadingDialog)
            LatteLoader.showLoading(loadingDialog)
    }

    protected open fun dismissLoading() {
        if (showLoadingDialog)
            LatteLoader.dismissLoading(loadingDialog)
    }




    @LayoutRes
    protected abstract fun attachLayoutRes(): Int

    protected abstract fun attachVMClass(): Class<VM>?

    protected abstract fun initView()

    /** 顶部状态栏 **/
    protected open fun initBar() {}
    /** 初始化数据 **/
    protected open fun initData() {}
    /** 设置事件监听 **/
    protected open fun initClickListener() {}
    /** 网络请求数据 **/
    protected open fun initRequestObserver() {}
    /** 页面跳转返回监听 **/
    protected open fun initResultLauncher() {}
    /** 注销页面跳转返回监听 **/
    protected open fun unregisterResultLauncher() {}

    /** 请求出错，如需处理。可以单独处理 比如出错后关闭页面或者其他。。。 **/
    protected open fun onError(error: ResponseThrowable) = Unit

    @SuppressWarnings("WeakerAccess")
    /** 是否可以使用沉浸式  */
    protected fun isImmersionBarEnabled(): Boolean {
        return true
    }
    private fun statusBarDarkFont(): Boolean {
        return false
    }
    open fun initImmersionBar() {
        //在BaseActivity里初始化
//        mImmersionBar = ImmersionBar.with(this) //                .statusBarColor(R.color.white)
//            .statusBarDarkFont(true, 0.2f)
//            .navigationBarColor(R.color.white)
//        mImmersionBar?.run { init() }

        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar
            .with(this)
            .statusBarDarkFont(statusBarDarkFont())
        mImmersionBar?.init()
    }

    //页面跳转返回带回来的数据
    open fun getActivityResultLauncher(resultCallback: (resultCode: Int, data: Intent?) -> Unit): ActivityResultLauncher<Intent> {
        return registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            resultCallback.invoke(result.resultCode, result.data)
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_UP) {
            val v = currentFocus
            // 如果不是落在EditText区域，则需要关闭输入法
            if (KeyBoardUtil.isHideKeyboard(v, ev)) {
                KeyBoardUtil.hideKeyBoard(this, v)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                onBackPressed()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    /** 隐藏软键盘 **/
    protected open fun hideKeyboard(view: View) {
        val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

    override fun finish() {
        AppConfig.getActivityManager()?.popActivity(this)
        super.finish()
    }
    override fun onDestroy() {
        mImmersionBar?.destroy()
        rxBusSubscription?.unsubscribe()
        unregisterResultLauncher()
        lifecycle.removeObserver(mViewModel)
        if(::binding.isInitialized){
            binding.unbind()
        }
        super.onDestroy()
    }


    /**
     * 跳转
     *
     * @param cls
     */
    protected open fun startActivity(clazz: Class<Any>) {
        startActivity(clazz, null)
    }

    /**
     * 跳转传参数
     *
     * @param cls
     * @param bundle
     */
    protected open fun startActivity(cls: Class<Any>?, bundle: Bundle?) {
        val intent = Intent(this, cls)
        if (bundle != null) {
            intent.putExtras(bundle)
        }
        startActivity(intent)
    }

    /**
     * 跳转
     * finish
     *
     * @param cls
     */
    protected open fun startActivityFinish(cls: Class<Any>?) {
        startActivityFinish(cls, null)
    }

    /**
     * 跳转传参数
     * finish
     *
     * @param cls
     * @param bundle
     */
    protected open fun startActivityFinish(cls: Class<Any>?, bundle: Bundle?) {
        val intent = Intent(this, cls)
        if (bundle != null) {
            intent.putExtras(bundle)
        }
        startActivity(intent)
        finish()
    }


    /**
     * 复制
     *
     * @param context
     * @param copyField
     */
    fun CopyToClipboard(context: Context, copyField: String?) {
        val myClip = ClipData.newPlainText("text", copyField)
        val myClipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        myClipboard.setPrimaryClip(myClip)
        showToast("复制成功")

    }

}